import { getItemNums } from '@/components/DataStandard/WorkForm/Utils';
import FormItem from '@/components/DataStandard/WorkForm/Viewer/formItem';
import { OrderSyncProperties } from '@/config/column';
import OrderView from '@/executor/open/form/detail/OrderView';
import useStorage from '@/hooks/useStorage';
import { model, schema } from '@/ts/base';
import { IApplication, IBelong, ITarget } from '@/ts/core';
import { Button, Divider, Space } from 'antd';
import Toolbar, { Item } from 'devextreme-react/toolbar';
import React, { useEffect, useState } from 'react';
import styles from './index.module.less';
import orgCtrl from '@/ts/controller';
import { command } from '@/ts/base';
import { Work } from '@/ts/core/work';
import OpenFileDialog from '@/components/OpenFileDialog';
import { EditOutlined } from '@ant-design/icons';

interface OrderIWork {
  seller_order_task?: schema.XWorkDefine;
  buyer_order_task?: schema.XWorkDefine;
}
interface IProps {
  height?: string;
  current: schema.XOrder;
}
// 订单视图
const OrderViewer: React.FC<IProps> = ({ current }) => {
  const [target, setTarget] = useState<ITarget>();
  const [visible, setVisible] = useState(false);
  const [isSeller, setIsSeller] = useState(false);
  const [fields, setFields] = useState<any[]>([]);
  const [colNum, setColNum] = useStorage('workFormColNum', '一列');

  useEffect(() => {
    const fields = OrderSyncProperties().filter((item: any) => {
      item['options'] = {
        ...(item['options'] || {}),
        readOnly: true,
      };
      return item.code !== 'itemList';
    });
    setFields(fields);
  }, []);

  useEffect(() => {
    if (current) {
      try {
        const target = orgCtrl.targets.find((item) => item.id === current.belongId);
        target && setTarget(target);
        const itemBelonging = current.itemList[0]['belongId'];
        const orderBelonging = current.belongId;
        setIsSeller(itemBelonging === orderBelonging);
      } catch (error) {
        setIsSeller(false);
      }
    }
  }, [current]);

  const handleData = async () => {
    const taskKey = isSeller ? 'seller_order_task' : 'buyer_order_task';
    if (target && target.metadata && taskKey in target?.metadata) {
      const metadata = target.metadata as { [key: string]: any };
      if (metadata[taskKey]) {
        const workInstance = new Work(metadata[taskKey], {
          directory: target?.directory,
        } as IApplication);
        setExtraParams(workInstance);
        command.emitter('executor', 'open', workInstance);
        return;
      }
    }
    const work: OrderIWork | null | undefined = await target?.cacheObj.get(
      'orderProcessingTasks',
    );
    if (work && typeof work === 'object' && work != null) {
      if (taskKey in work && work[taskKey]) {
        const workInstance = new Work(work[taskKey], {
          directory: target?.directory,
        } as IApplication);
        setExtraParams(workInstance);
        command.emitter('executor', 'open', workInstance);
        return;
      } else {
        setVisible(true);
      }
    } else {
      setVisible(true);
    }

    setVisible(true);
  };

  const setExtraParams = (instance: Work) => {
    instance.setExtraParams({
      id: current.id,
      type: 'orderHandler',
    });
  };

  return (
    <div className={styles['order-container']}>
      <Space size={20} direction="vertical" style={{ width: '100%' }}>
        <Toolbar style={{ marginBottom: '10px' }}>
          <Item
            location="after"
            locateInMenu="never"
            widget="dxSelectBox"
            options={{
              text: '项排列',
              value: colNum,
              items: getItemNums(),
              onItemClick: (e: { itemData: string }) => {
                setColNum(e.itemData);
              },
            }}
          />
        </Toolbar>
        <div style={{ display: 'flex', width: '100%', flexWrap: 'wrap', gap: 10 }}>
          <FormItem
            key={'name'}
            data={current}
            numStr={colNum}
            rules={[]}
            readOnly={false}
            field={
              {
                id: 'name',
                name: '名称',
                code: 'name',
                valueType: '描述型',
                remark: '数据的名称。',
                options: { hideField: true },
              } as model.FieldModel
            }
            belong={null as unknown as IBelong}
          />
          {fields.map((field) => {
            if (!('id' in field)) {
              return (
                <div key={field.name}>
                  <Divider type="vertical" />
                  <span>{field.name}</span>
                </div>
              );
            } else {
              return (
                <FormItem
                  key={field.id}
                  data={current}
                  numStr={colNum}
                  rules={[]}
                  field={field as model.FieldModel}
                  belong={null as unknown as IBelong}
                />
              );
            }
          })}
        </div>

        <OrderView thingData={current} />
      </Space>

      <div className={styles['order-toolbar']}>
        <Button
          type="primary"
          className={styles['order-toolbar-btn']}
          onClick={handleData}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <EditOutlined style={{ fontSize: '12px' }} />
            &nbsp; 去处理
          </div>
        </Button>
      </div>

      {visible && (
        <OpenFileDialog
          title="选择办事"
          accepts={['办事']}
          rootKey={target?.directory?.spaceKey || ''}
          allowInherited
          multiple={false}
          onOk={async (files) => {
            setVisible(false);
            const workInstance = files[0] as unknown as Work;
            setExtraParams(workInstance);
            command.emitter('executor', 'open', workInstance);
          }}
          onCancel={() => setVisible(false)}
        />
      )}
    </div>
  );
};

export default OrderViewer;
